package com.stylefeng.guns.modular.huamao.controller;

import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@SuppressWarnings("all")
@Controller
@RequestMapping("/app")
public class AppShopsController extends BaseController {
    @Autowired
    private IAppShopsService iAppShopsService;
    @Autowired
    private IAppUsersRealnameService iAppUsersRealnameService;
    @Autowired
    private IAppShopApproveService iAppShopApproveService;
    @Autowired
    private IAppAccountService iAppAccountService;
    @Autowired
    private IAppShopApplysService iAppShopApplysService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private ISktShopsService sktShopsService;
    @Autowired
    private ISktSysConfigsService sktSysConfigsService;

    /**
     * 商家基本信息(ZJF)
     * @param shopId
     * @return
     */
    @RequestMapping("/shops/storeInfo")
    @ResponseBody
    public AppResult storeInfo(@ModelAttribute("shopId") String shopId){
        try{
            Map<String,Object> sktShops=iAppShopsService.selectUsersShopsByUserShopId(shopId);
            if (Integer.parseInt(sktShops.get("shopStatus").toString())==0){
                return AppResult.ERROR("该商家已被禁用");
            }
            if (Integer.parseInt(sktShops.get("dataFlag").toString())==0){
                return AppResult.ERROR("该商家已失效");
            }
            CommonModel commonModel = new CommonModel();
            sktShops.put("scoreRatio",sktShops.get("scoreRatio")+"");
            sktShops.put("userPhoto", commonModel.getOSS_DOM()+sktShops.get("userPhoto"));
            sktShops.put("userId",sktShops.get("userId").toString());
            return AppResult.OK("获取成功",sktShops);
        }catch (Exception e){
            e.printStackTrace();
            return  AppResult.ERROR("获取失败",-1);
        }
    }

    /**
     * 申请联盟1（ZJF）
     * @return
     */
    @RequestMapping("/shops/userRealName")
    @ResponseBody
    public AppResult userRealName(){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            UsersRealname usersRealname = iAppUsersRealnameService.selectUsersRealNameByUserId(user.getUserId());
            Map<String, Object> map = new HashMap<>();
            CommonModel commonModel = new CommonModel();
            map.put("trueName",usersRealname.getTrueName());
            map.put("cardID",usersRealname.getCardID());
            map.put("handCardUrl",commonModel.getOSS_DOM()+usersRealname.getHandCardUrl());
            return AppResult.OK("获取成功",map);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.OK("获取失败",-2);
        }

    }

    /**
     * 申请联盟2（ZJF）
     * @param provinceId
     * @param cityId
     * @param areaId
     * @param isLegal
     * @param legalPerson
     * @param IDnumber
     * @param companyName
     * @param licenseNo
     * @param companyType
     * @param industry
     * @param shopName
     * @param address
     * @param telephone
     * @param licenseMerge
     * @param licenseImg
     * @param legalPersonImg
     * @param logo
     * @param codeImg
     * @param taxImg
     * @param authorizationImg
     * @return
     */
    @RequestMapping("/shops/shopsOffApply")
    @ResponseBody
    @Transactional
    public AppResult shopsOffApply(@ModelAttribute("provinceId")String provinceId,@ModelAttribute("cityId")String cityId,@ModelAttribute("areaId")String areaId,
                                   @ModelAttribute("isLegal")String isLegal,@ModelAttribute("legalPerson")String legalPerson,@ModelAttribute("IDnumber")String IDnumber,
                                   @ModelAttribute("companyName")String companyName,@ModelAttribute("licenseNo")String licenseNo,@ModelAttribute("companyType")String companyType,
                                   @ModelAttribute("industry")String industry,@ModelAttribute("shopName")String shopName,@ModelAttribute("address")String address,
                                   @ModelAttribute("telephone")String telephone,@ModelAttribute("licenseMerge")String licenseMerge,@ModelAttribute("licenseImg")String licenseImg,
                                   @ModelAttribute("legalPersonImg")String legalPersonImg,@ModelAttribute("logo")String logo,@ModelAttribute("codeImg")String codeImg,
                                   @ModelAttribute("taxImg")String taxImg,@ModelAttribute("authorizationImg")String authorizationImg){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            SktShopApprove sktShopApprove=new SktShopApprove();
            if (!MSGUtil.verify(IDnumber)){
            return  AppResult.ERROR("身份证格式不正确",-1);
        }
        if (licenseMerge=="0"){
            if (MSGUtil.isEmpty(codeImg)){
                return AppResult.ERROR("请上传组织机构代码证",-1);
            }
            if (MSGUtil.isEmpty(taxImg)){
                return AppResult.ERROR("请上传综合服务费务登记证",-1);
            }
        }

        if (isLegal=="0"){
            if (MSGUtil.isEmpty(authorizationImg)){
                return AppResult.ERROR("请上传授权书",-1);
            }
        }
        sktShopApprove.setUserId(user.getUserId());
        sktShopApprove.setProvinceId(Integer.parseInt(provinceId));
        sktShopApprove.setAreaId(Integer.parseInt(areaId));
        sktShopApprove.setCityId(Integer.parseInt(cityId));
        sktShopApprove.setIDnumber(IDnumber);
        sktShopApprove.setCodeImg(codeImg);
        sktShopApprove.setLicenseMerge(Integer.parseInt(licenseMerge));
        sktShopApprove.setTaxImg(taxImg);
        sktShopApprove.setAuthorizationImg(authorizationImg);
        sktShopApprove.setIsLegal(Integer.parseInt(isLegal));
        sktShopApprove.setCreateTime(new Date());
        sktShopApprove.setLegalPerson(legalPerson);
        sktShopApprove.setCompanyName(companyName);
        sktShopApprove.setLicenseNo(licenseNo);
        sktShopApprove.setCompanyType(Integer.parseInt(companyType));
        sktShopApprove.setIndustry(Integer.parseInt(industry));
        sktShopApprove.setShopName(shopName);
        sktShopApprove.setAddress(address);
        sktShopApprove.setTelephone(telephone);
        sktShopApprove.setLicenseImg(licenseImg);
        sktShopApprove.setLegalPersonImg(legalPersonImg);
        sktShopApprove.setLogo(logo);
        Map<String, Object> msg = Validate.validate(sktShopApprove);
        String msgs = msg.get("Msg").toString();
        if(!msgs.equals("1")){
            return AppResult.ERROR(msgs,-3);
        }
            SktShopApprove sktShopApproves = iAppShopApproveService.selectShopApproveByUserId(user.getUserId());
            if (MSGUtil.isEmpty(sktShopApproves)){//第一次申请
                boolean insert = iAppShopApproveService.insert(sktShopApprove);
                if (insert){
                return AppResult.OK("成功",null);
                }
            }
            if (sktShopApproves.getShopStatus()==-1){// 被拒绝，再次申请 -1拒绝0未审核1已审核
                sktShopApprove.setShopStatus(0);
                sktShopApprove.setApplyId(sktShopApproves.getApplyId());
                boolean b = iAppShopApproveService.updateById(sktShopApprove);
                if (b){
                    return AppResult.OK("成功",null);
                }
            }
            if (sktShopApproves.getShopStatus()==1){//已申请通过
                return AppResult.OK("已申请通过，无需再次申请",null);
            }else {
                return AppResult.ERROR("申请中，不能再次申请",-1);
            }
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("失败",-2);
        }
    }

    /**
     *
     *申请线上商城1（ZJF）
     * @return
     */
    @RequestMapping("/shops/shopsOnEnter")
    @ResponseBody
    public AppResult shopsOnEnter(){
        try{
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            Account account = iAppAccountService.selectAccountByUserId(user.getUserId());
            SktShops sktShopses = new SktShops();
            sktShopses.setShopId(account.getShopId());
            SktShops sktShops = iAppShopsService.selectById(sktShopses);
            Map<String, Object> map = new HashMap<>();
            map.put("legalPerson",sktShops.getLegalPerson());
            map.put("IDnumber",sktShops.getIDnumber());
            map.put("companyName",sktShops.getCompanyName());
            map.put("licenseNo",sktShops.getLicenseNo());
            map.put("shopName",sktShops.getShopName());
            map.put("telephone",sktShops.getTelephone());
            return AppResult.OK("成功",map);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("失败",-2);
        }
    }

    /**
     * 申请线上商城2（ZJF）
     * @return
     */
    @RequestMapping("/shops/shopsOnApply")
    @ResponseBody
    @Transactional
    public AppResult shopsOnApply(){
        try{
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            Account account = iAppAccountService.selectAccountByUserId(user.getUserId());
            SktShopApplys sktShopApplyses = new SktShopApplys();
            sktShopApplyses.setUserId(user.getUserId());
            sktShopApplyses.setCreateTime(new Date());
            sktShopApplyses.setApplyDesc("");
            sktShopApplyses.setApplyStatus(1);
            sktShopApplyses.setDataFlag(1);
            sktShopApplyses.setShopId(account.getShopId());
            SktShopApplys sktShopApplys = iAppShopApplysService.selectShopApplysByUserId(user.getUserId());
            if (MSGUtil.isBlank(sktShopApplys)){//第一次申请
                boolean insert = iAppShopApplysService.insert(sktShopApplyses);
                if (insert){
                    return AppResult.OK("成功",null);
                }
            }
            if (sktShopApplys.getApplyStatus()==2){//被拒绝，再次申请
                sktShopApplyses.setApplyId(sktShopApplys.getApplyId());
                sktShopApplyses.setApplyStatus(1);
                boolean b = iAppShopApplysService.updateById(sktShopApplyses);
                if (b){
                    return AppResult.OK("成功",null);
                }
            }
            if (sktShopApplys.getApplyStatus()==1){
                return AppResult.ERROR("申请中,不能再次申请",-1);
            }else {
                return AppResult.OK("已申请通过,无需再次申请",null);
            }
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("失败",-1);
        }
    }

    /**
     * 店铺详情
     * @param shopId
     * @return
     */
    @RequestMapping("/shops/shopsDetailed")
    @ResponseBody
    public AppResult appShopsDetailed(@ModelAttribute("shopId")Integer shopId){
        Map<String,Object> map = sktShopsService.appShopsDetailed(shopId);
        Integer code = (Integer) map.get("code");
        if(code == 0){
            String msg = (String)map.get("msg");
            return AppResult.ERROR(msg);
        }
        return AppResult.OK("查询成功",map);
    }
    /**
     * 获取收款二维码
     * @param shopId
     * @return
     */
    @RequestMapping("/shops/getQR")
    @ResponseBody
    public AppResult getQR(){
        Map<String, Object> map = sktSysConfigsService.getQR();
        if (map!=null && map.size()>0){
            String alipayQR="";
            String weChatQR ="";
            String alipayQRId ="";
            String weChatQRId = "";
            if(!"".equals(map.get("alipayQR").toString())&& map.get("alipayQR").toString()!=null){
                alipayQR = map.get("alipayQR").toString();
            }
            if(!"".equals( map.get("weChatQR").toString())&& map.get("weChatQR").toString()!=null){
                weChatQR = map.get("weChatQR").toString();
            }

            if(!"".equals(map.get("alipayQRId").toString())&& map.get("alipayQRId").toString()!=null){
                alipayQRId = map.get("alipayQRId").toString();
            }
            if(!"".equals( map.get("weChatQRId").toString())&& map.get("weChatQRId").toString()!=null){
                weChatQRId = map.get("weChatQRId").toString();
            }
            map.put("weChatQR",weChatQR);
            map.put("alipayQR",alipayQR);
        }

        return AppResult.OK(map);
    }
}
